package cn.team11.util.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.allenliu.versionchecklib.core.AVersionService;
import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;

import org.json.JSONObject;

import cn.team11.util.T11Log;
import cn.team11.util.T11Util;

public class T11UpdateService extends AVersionService {
    public T11UpdateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static void startVersionCheck(Context ctx, Class customDownloadActivityClass) {
        T11Log.d("开始版本检测");


        VersionParams.Builder builder = new VersionParams.Builder().setRequestUrl("http://sds-app.oss.team11.cn/apk-release/t11-%E6%A0%87%E5%87%86/updateInfo.json")
                .setService(T11UpdateService.class);
        if (customDownloadActivityClass != null) {
            builder.setCustomDownloadActivityClass(customDownloadActivityClass);
        }
        AllenChecker.startVersionCheck(ctx, builder.build());
    }

    public static void startVersionCheck(Context ctx) {
        startVersionCheck(ctx, null);
    }

    @Override
    public void onResponses(AVersionService service, String response) {
        //这里你解析response，判断是否更新以及是否强制更新，将参数传过去
        T11Log.d("版本更新response:" + response);
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(response);
        boolean isForceUpdate = obj.getBoolean("isForceUpdate");
        int latestVersion = obj.getInteger("latestVersion");
        String latestVersionUrl = obj.getString("latestVersionUrl");

        T11Log.d("isForceUpdate = " + isForceUpdate + ", latestVersion = " + latestVersion + ", latestVersionUrl = " + latestVersionUrl);

        Bundle bundle = new Bundle();
        bundle.putBoolean("isForceUpdate", isForceUpdate);
        PackageInfo info = T11Util.getPkgInfo(this);
        if (latestVersion > info.versionCode) {
            showVersionDialog(latestVersionUrl, "软件有更新了", "是否更新", bundle);
        }
    }
}
